package org.cttic.visualization.visualization.util.sevenUtil;

import org.cttic.visualization.visualization.common.module.roadConditionsListData;
import org.cttic.visualization.visualization.util.DateUtil;
import org.cttic.visualization.visualization.util.GpsCoordinateUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.core.CountRequest;
import org.elasticsearch.client.core.CountResponse;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.BucketOrder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * @author shkstart
 * @create 2020-06-29 15:21
 */
@Component
public class QueryEs_roadConditionsUtil {
    @Autowired
    private RestHighLevelClient restHighLevelClient;
    public void queryEs(String startTime,String endTime,String provinceId,String gantryType,List<roadConditionsListData.ConditionsList> list){

        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        // 搜索方式
        // matchAllQuery搜索全部
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        boolQueryBuilder.must(QueryBuilders.rangeQuery("tansTime")
                .gt(startTime)
                .lt(endTime));
        boolQueryBuilder.must(QueryBuilders.rangeQuery("speed")
                .gt("0")
                .lt("200"));
        //todo 判断是否按gantryType查询
        if(gantryType!=null){
            boolQueryBuilder.must(QueryBuilders.termQuery("gantryType",gantryType));
        }

        //todo 判断是否查询全国
        if (provinceId!=null&&!provinceId.contains("|")){
            //单个省份
            boolQueryBuilder.must(QueryBuilders.rangeQuery("curareacode").gte(Integer.parseInt(provinceId)*10000).lt(provinceId+9999));
        }else if (provinceId!=null&&provinceId.contains("|")){
            //多个省份
            String[] split = provinceId.split("\\|");
            for (int i=0;i<split.length;i++){
                String province = split[i];
                boolQueryBuilder.must(QueryBuilders.rangeQuery("curareacode").gte(Integer.parseInt(provinceId)*10000).lt(province+9999));
            }
        }
        searchSourceBuilder.aggregation(AggregationBuilders.terms("groupBy_gantryId").field("gantryId").order(BucketOrder.key(true)));
        searchSourceBuilder.aggregation(AggregationBuilders.avg("avg").field("speed"));
//        searchSourceBuilder.sort("avg",SortOrder.ASC);
//        searchSourceBuilder.aggregation(AggregationBuilders.cardinality("qc_vehicleNo").field("vehicleNo"));
        searchSourceBuilder.query(boolQueryBuilder);
        searchSourceBuilder.size(20);
        String month = DateUtil.StampToMonth(System.currentTimeMillis());
        // 执行搜索,向ES发起http请求
        SearchRequest Request = new SearchRequest("trip_incomplete_"+month,"trip_info_"+month);
        Request.types("_doc");

        Request.source(searchSourceBuilder);
        SearchResponse response = null;
        try {
            response = restHighLevelClient.search(Request, RequestOptions.DEFAULT);
            SearchHit[] hits = response.getHits().getHits();
            for (SearchHit hit : hits) {
                roadConditionsListData.ConditionsList conditionsList = new roadConditionsListData.ConditionsList();
                Map<String, Object> sourceAsMap = hit.getSourceAsMap();
                String gantryId = sourceAsMap.get("gantryId").toString();
                String pointName = sourceAsMap.get("pointName").toString();
                String travelId = sourceAsMap.get("travelId").toString();
                String tansTime = sourceAsMap.get("tansTime").toString();
                String speed = sourceAsMap.get("speed").toString();
                String point = sourceAsMap.get("point").toString();
                String lat=null;
                String lon=null;
                if(point!=null&&point.contains(",")){
//                    System.out.println("point:"+point);
                    //point:{lon=115.85115, lat=26.358266}
                    String substring = point.substring(1, point.length() - 1);
                    String[] split = substring.split(", ");
                     lon = split[0].substring(4);
                     lat = split[1].substring(4);
                    System.out.println("lon:"+lon+",lat:"+lat);

                }
                long inOrOut = getInOrOut(travelId, tansTime);
                if(inOrOut>0){
                    conditionsList.setDirection("1");
                }else{
                    conditionsList.setDirection("2");
                }
                long size = getSize(travelId, startTime, endTime);
                //收费站
                int speed2 = Integer.parseInt(speed);
//                if(gantryType.equals("1")){
//                    if(size>=20&&speed2>=0&&speed2<=10){
//                        conditionsList.setTrafficLevel("1");
//                    }else if (size>=10&&speed2>=0&&speed2<=10){
//                        conditionsList.setTrafficLevel("2");
//                    }else if (size>=5&&speed2>=0&&speed2<=10){
//                        conditionsList.setTrafficLevel("3");
//                    }else if (size>=1&&speed2>=0&&speed2<=10){
//                        conditionsList.setTrafficLevel("4");
//                    }else {
//                        conditionsList.setTrafficLevel("5");
//                    }
                if(gantryType.equals("1")){
                    if(speed2>=0&&speed2<=5){
                        conditionsList.setTrafficLevel("1");
                    }else if (speed2>=6&&speed2<=10){
                        conditionsList.setTrafficLevel("2");
                    }else if (speed2>=11&&speed2<=20){
                        conditionsList.setTrafficLevel("3");
                    }else if (speed2>=21&&speed2<=30){
                        conditionsList.setTrafficLevel("4");
                    }else {
                        conditionsList.setTrafficLevel("5");
                    }
                //门架
                }else {
                    if(size>=10&&speed2>=0&&speed2<=10){
                        conditionsList.setTrafficLevel("1");
                    }else if (size>=10&&speed2>=10&&speed2<=20){
                        conditionsList.setTrafficLevel("2");
                    }else if (size>=10&&speed2>=20&&speed2<=30){
                        conditionsList.setTrafficLevel("3");
                    }else if (size>=1&&speed2>=40&&speed2<=80){
                        conditionsList.setTrafficLevel("4");
                    }else {
                        conditionsList.setTrafficLevel("5");
                    }
                }
                conditionsList.setProvinceId(provinceId);
                conditionsList.setPointType(gantryType);
                conditionsList.setGantryId(gantryId);
                conditionsList.setGantryName(pointName);
                conditionsList.setLat(GpsCoordinateUtils.calWGS84toGCJ02Lat(Double.parseDouble(lat),Double.parseDouble(lon))+"");
                conditionsList.setLng(GpsCoordinateUtils.calWGS84toGCJ02Log(Double.parseDouble(lat),Double.parseDouble(lon))+"");
                conditionsList.setReportTime(DateUtil.timeToT(tansTime));

                list.add(conditionsList);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("路况列表个数：***********"+list.size());
//        Map<String, Aggregation> stringAggregationMap1=null;
//        if(response.getAggregations()!=null){
//            stringAggregationMap1 = response.getAggregations().asMap();
//        }
//        ParsedCardinality group_by_state1 = (ParsedCardinality) stringAggregationMap1.get("groupBy_gantryId");
//        long value1 = group_by_state1.getValue();



    }
    private long getInOrOut(String travelId,String transTime){
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        // 搜索方式
        // matchAllQuery搜索全部

        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        boolQueryBuilder.must(QueryBuilders.termsQuery("travelId",travelId));
        boolQueryBuilder.must(QueryBuilders.rangeQuery("tansTime")
                .gt(transTime));
        searchSourceBuilder.query(boolQueryBuilder);
        String month = DateUtil.StampToMonth(System.currentTimeMillis());
        CountRequest countRequest = new CountRequest("trip_incomplete_"+month,"trip_info_"+month);
        countRequest.types("_doc");

        countRequest.source(searchSourceBuilder);
        CountResponse count = null;
        try {
            count = restHighLevelClient.count(countRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("查询结果："+count.getCount());

        return count.getCount();
    }
    private long getSize(String travelId,String startTime,String endTime){
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        // 搜索方式
        // matchAllQuery搜索全部
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        boolQueryBuilder.must(QueryBuilders.termsQuery("travelId",travelId));
        boolQueryBuilder.must(QueryBuilders.rangeQuery("tansTime")
                .gt(startTime).lt(endTime));
        searchSourceBuilder.query(boolQueryBuilder);
        String month = DateUtil.StampToMonth(System.currentTimeMillis());
        CountRequest countRequest = new CountRequest("trip_incomplete_"+month,"trip_info_"+month);
        countRequest.types("_doc");

        countRequest.source(searchSourceBuilder);
        CountResponse count = null;
        try {
            count = restHighLevelClient.count(countRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("查询结果："+count.getCount());

        return count.getCount();
    }
}
